﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DotNetStar.TheKing.Web.Pages.User.Setting
{
    using DotNetStar.TheKing.Models;
    using Filters;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using System.ComponentModel.DataAnnotations;
    using System.IO;

    [OwnPage]
    public class ChangeAvatarModel : PageModel
    {
        private readonly UserService _userService;
        private readonly IHostingEnvironment _env;
        public ChangeAvatarModel(UserService userService,IHostingEnvironment env)
        {
            _userService = userService;
            _env = env;
        }
        
        [BindProperty]
        [Display(Name ="上传图片")]
        [Required(ErrorMessage ="{0}不能为空")]
        [DataType(DataType.Upload)]
        [FileExtensions(Extensions ="jpg,png")]        
        public IFormFile Avatar { get; set; }

        public string[] Extension => new[] { ".png", ".jpg" };
        
        public IActionResult OnGetAsync()
        {
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "表单验证有错误");
                return Page();
            }

            if (this.Avatar == null)
            {
                ModelState.AddModelError("", "请选择图片");
                return Page();
            }

            var maxSize = 1024 * 1024 * 2;
            if (this.Avatar.Length > maxSize)
            {
                ModelState.AddModelError("", $"图片尺寸不能超过{maxSize}MB");
                return Page();
            }

            var fileExtension = Path.GetExtension(this.Avatar.FileName);
            if (!this.Extension.Contains(fileExtension))
            {
                ModelState.AddModelError("", $"不支持当前文件的扩展名");
                return Page();
            }

            var user = await _userService.GetByIdAsync(User.Identity.UserId());
            if (user == null)
            {
                return RedirectToPage("/Error", new { message = "当前用户不存在或已被删除" });
            }


            var buffer = new byte[this.Avatar.OpenReadStream().Length];

            try
            {
                var directory = $"{_env.WebRootPath}/upload/avatar/{User.Identity.UserId()}";
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                FileStream fileStream = null;

                var filePath = $"{directory}/avatar{Path.GetExtension(Avatar.FileName)}";
                var fileInfo = new FileInfo(filePath);
                if (!fileInfo.Exists)
                {
                    fileStream= fileInfo.Create();
                }
                else
                {
                    fileStream = fileInfo.OpenWrite();
                }

                this.Avatar.CopyTo(fileStream);
                fileStream.Write(buffer, 0, buffer.Length);
                fileStream.Flush();
                fileStream.Close();

                user.AvatarUrl = filePath.Replace(_env.WebRootPath,"");
                await _userService.UpdateUserAsync(user);

                User.Identity.UpdateClaim(nameof(Domain.User.AvatarUrl), user.AvatarUrl);
                

                ViewData["Success"] = true;
                return Page();

            }
            catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return Page();
            }
        }
    }
}